package susebs.pb.travel_server.controller;


import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import susebs.pb.travel_server.domain.Result;
import susebs.pb.travel_server.entity.Users;
import susebs.pb.travel_server.service.UsersService;

import javax.annotation.Resource;

/**
 * 登陆注册
 * 整个后端都没有问题，问题就出在前端传参上，参数传递不过来
 */
@RestController
@CrossOrigin
public class LoginController {

    @Resource
    private UsersService usersService;

    /**
     * 注册
     * 1.检查账号是否被注册
     * 2.注册账号
     * @param user 待注册用户账号和密码
     * @return 是否注册成功的消息
     */
    @PostMapping("/register")
    public Result register(@RequestBody Users user){
        if(user.getUserAccount() == null || user.getPassword() == null){
            return Result.buildFail("请设置账号和密码！");
        }

        int register = usersService.register(user);
        if(register == 1) return Result.buildSuccess();
        return  Result.buildFail("账号已存在，请重新注册！");
    }

    /**
     * 登录
     * @param user 待登录用户账号和密码
     * @return 登录成功：用户数据；登录失败：返回消息
     */
    @PostMapping("/login")
    public Result login(@RequestBody Users user){
        if(user.getUserAccount() == null || user.getPassword() == null){
            return Result.buildFail("请输入账号或者密码！");
        }

        int login = usersService.login(user);
        //登陆成功后仅存储用户id，因为后面用户信息可能更改，用户数据每次渲染都实时请求
        if(login == 1)return Result.buildSuccess(usersService.queryUser(user));
        return Result.buildFail("账号或者密码输入错误，请重试！");
    }
}
